package com.example.tdemo.thread.cas;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 *
 * @author: tzb
 */
public class CASLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();


    void tryLock() {
        Thread thread = Thread.currentThread();

        System.out.println(thread.getName() + "\t come in");

        while (!atomicReference.compareAndSet(null, thread)) {

            System.out.println(thread.getName() + "\t try lock failed,waiting");
        }
    }

    void unLock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(thread.getName() + "\t invoked unLock()");
    }

    public static void main(String[] args) {
        CASLockDemo lockDemo = new CASLockDemo();
        new Thread(() -> {
            lockDemo.tryLock();

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lockDemo.unLock();
        }, "A").start();

        new Thread(() -> {
            lockDemo.tryLock();


            lockDemo.unLock();
        }, "B").start();
    }
}
